<?php


namespace EchoPHP\Http\Response;


use EchoPHP\Http\Response;

class StreamedResponse extends Response {

    protected $callback;
    protected $streamed;
    protected $headersSent;

    public function __construct(callable $callback = null, int $status = 200, array $headers = []) {
        parent::__construct(null, $status, $headers);
        if (null !== $callback) {
            $this->setCallback($callback);
        }

        $this->streamed = false;
        $this->headersSent = false;
    }

//    public static function create(callable $callback = null, int $status = 200, array $headers = []) {
//        return new static($callback, $status, $headers);
//    }

    /**
     * 设置回调函数
     * @param callable $callback
     * @return $this
     */
    public function setCallback(callable $callback) {
        $this->callback = $callback;
        return $this;
    }

    /**
     * 发送响应头
     * @return $this|Response
     */
    public function sendHeaders() {
        if ($this->headersSent) {
            return $this;
        }
        $this->headersSent = true;
        return parent::sendHeaders();
    }

    /**
     * 发送响应正文
     * @return $this|Response
     */
    public function sendContent() {
        if ($this->streamed) {
            return $this;
        }

        $this->streamed = true;

        if (null === $this->callback) {
            throw new \LogicException('流响应的回调不可为空');
        }

        ($this->callback)();

        return $this;
    }

    /**
     * 设置响应正文
     * @param $content
     * @return $this|Response
     */
    public function setContent($content) {
        if (null !== $content) {
            throw new \LogicException('流响应的响应正文不能自定义');
        }
        $this->streamed = true;
        return $this;

    }

    /**
     * 获取响应正文
     * @return bool|mixed
     */
    public function getContent() {
        return false;
    }


    public function setContentDisposition($disposition, $filename, $filenameFallback = '') {
        if (empty($filename)) {
            throw new \InvalidArgumentException('文件名不能为空');
        }
        if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || false !== strpos($filename, '%'))) {
            $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';

            for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
                $char = mb_substr($filename, $i, 1, $encoding);

                if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
                    $filenameFallback .= '_';
                } else {
                    $filenameFallback .= $char;
                }
            }
        }

        $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
        $this->headers->set('Content-Disposition', $dispositionHeader);

        return $this;
    }
}